package a66weding.com.jiehuntong.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;

import com.igexin.sdk.PushManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.ProvinceBean;
import a66weding.com.jiehuntong.beans.ProvinceCitySelectBean;
import a66weding.com.jiehuntong.beans.PushBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.beans.VersionBean;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.dao.db.address.AddressDao;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;

public class StartupActivity extends CommonActivity implements OnNetResultListener {
    private static final int SAVESUCESS = 1;
    private static final int SHOWTIME = 2;
    private static final int NOLOGIN = 3;
    private static final int DBSUCESS = 5;
    private static final int DBFAIL = 6;
    private static final int DBADDRESS = 7;
    public static final String DB_NAME = "hdjr.db";
    private List<ProvinceBean.DataBean> provinceList;
    private AddressDao addressDao;
    private boolean isSaveUser;
    private boolean isDbinit;
    private List<ProvinceCitySelectBean.ResultBean> result;
    private int versionCode;
    private Intent intent;
    private String content;
    private PushBean pushBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        // 初始化个推
        PushManager.getInstance().initialize(this.getApplicationContext());
        intent = getIntent();
        pushBean = (PushBean) intent.getSerializableExtra("pushBean");
        if (pushBean != null) {// 点击通知进入应用
            ((GlobalApplication) getApplication()).setDownNewVersion(false);
            Intent intent = new Intent(StartupActivity.this, MainActivity.class);
            intent.putExtra("pushBean", pushBean);
            startActivity(intent);
            finish();
        } else {
            setContentView(R.layout.activity_startup);
            mHandler.sendEmptyMessageDelayed(SHOWTIME, 3000);
            initdata();
            getVersionInfo();
        }
    }

    /**
     * 用户，地址数据
     */
    private void initdata() {
        boolean islogin = CacheUtils.getBooleanFromCache(this, CacheUtils.islogin);
        if (islogin) {
            //读取本地缓存数据作为
//            String stringFromCache = CacheUtils.getStringFromCache(StartupActivity.this, RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE);
//            Gson gson = new Gson();
//            User user = gson.fromJson(stringFromCache, User.class);
//            DataWareHourse.getInstance().setmUser(user);
            //判断下缓存的用户信息是否存在,防止用户删除后进入应用,登录状态存在,但是信息不存在后的空指针异常
            User user = DataWareHourse.getInstance().getmUser();
            if (user != null) {//重新获取最新用户信息
                getUserInfo();
            } else {
                CacheUtils.setBooleanToCache(this, CacheUtils.islogin, false);
                ((GlobalApplication) getApplication()).setLogin(false);
            }
        } else {
            CacheUtils.setBooleanToCache(this, CacheUtils.islogin, false);
            ((GlobalApplication) getApplication()).setLogin(false);
        }
        //数据库：
        downloadDatabase();
        boolean isAddressDbCreate = CacheUtils.getBooleanFromCache(this, "isAddressDbCreate");
        if (!isAddressDbCreate) {
            addressDao = new AddressDao(this);
            String url = RequestCode.get_PCAList;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, ProvinceCitySelectBean.class, RequestCode.get_PCAList);
            HttpHandleUtil.executeCommonGet(this, httpRequestBean);
        }
    }

    /**
     * 用户信息（根据用户id获取用户信息）
     */
    private void getUserInfo() {
        int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        String url = Url.GETUSERINFO + uId;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                StartupActivity.this, User.class, "");
        HttpHandleUtil.executeCommonPost(StartupActivity.this, httpRequestBean);
    }

    /**
     * 获取版本信息
     */
    private void getVersionInfo() {
        versionCode = CUtils.getVersionCode(this);
        String url = RequestCode.GET_APP_NEW_VERSION;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, VersionBean.class,
                RequestCode.GET_APP_NEW_VERSION);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof User) {
            User userData = (User) data;
            switch (userData.getResCode()) {
                case "0000":
                    saveUserInfo(userData);
                    mHandler.sendEmptyMessage(SAVESUCESS);
                    break;
            }
        } else if (data instanceof ProvinceCitySelectBean) {
            ProvinceCitySelectBean selectData = (ProvinceCitySelectBean) data;
            switch (selectData.getResCode()) {
                case "0000":
                    result = selectData.getResult();
                    mHandler.sendEmptyMessage(DBADDRESS);
                    break;
            }

        } else if (data instanceof ProvinceBean) {
            ProvinceBean proData = (ProvinceBean) data;
            switch (proData.getResCode()) {
                case "0000":
                    provinceList = proData.getData();
                    break;
                default:
            }
        } else if (data instanceof VersionBean) {
            VersionBean versionBean = (VersionBean) data;
            switch (versionBean.getResCode()) {
                case "0000":
                    if (versionBean != null) {
                        int new_versionCode = versionBean.getData().getNew_versionCode();
                        Log.e("Log", "StartupActivity onSucess: VersionBean=" + versionBean);
                        if (new_versionCode > versionCode) {
                            ((GlobalApplication) getApplication()).setDownNewVersion(true);
                            DataWareHourse.getInstance().setVersionBean(versionBean);
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        switch (errorBean.getErrorCode()) {
            case ErrorBean.NONET:
                break;
            default:
//                    CUtils.showToast("网络连接失败，请确认网络正常");
        }
    }

    private void saveUserInfo(User user) {
        if (user != null) {
            DataWareHourse.getInstance().setmUser(user);
            CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, user);
            ((GlobalApplication) getApplication()).setLogin(true);
            CacheUtils.setBooleanToCache(this, CacheUtils.islogin, true);
        }
    }


    //下载数据库
    private void downloadDatabase() {
        new Thread() {
            @Override
            public void run() {
                try {
                    copyDB(DB_NAME);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

            }
        }.start();

    }


    /**
     * 把assets目录下address.db拷贝到data/data/cn.itcast.mobilesafe/files/address.db
     */
    private void copyDB(String dbName) {
        File dbDir = FileUtil.getDbFile(this);
        File dbFile = new File(dbDir, dbName);
        if (dbFile.exists() && dbFile.length() > 0) {
            mHandler.sendEmptyMessage(DBSUCESS);
        } else {
            try {
                AssetManager asset = getResources().getAssets();
                InputStream is = asset.open(dbName);
                FileOutputStream fos = new FileOutputStream(dbFile);
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
                mHandler.sendEmptyMessage(DBSUCESS);
            } catch (Exception e) {
                mHandler.sendEmptyMessage(DBFAIL);
                e.printStackTrace();
            }
        }

    }

    private void initDataBase() {
        if (result != null) {
            boolean isAdd = addressDao.addAllAddress(result);
            if (isAdd) {
                CacheUtils.setBooleanToCache(this, "isAddressDbCreate", true);
            } else {
                CacheUtils.setBooleanToCache(this, "isAddressDbCreate", false);

            }
        }

    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SAVESUCESS:
                    isSaveUser = true;
                    break;
                case DBSUCESS:
                    CacheUtils.setBooleanToCache(StartupActivity.this, "holiday", true);
                    isDbinit = true;
                    break;
                case DBFAIL:
                    CacheUtils.setBooleanToCache(StartupActivity.this, "holiday", false);
                    break;
                case SHOWTIME:

                    Intent intent = new Intent(StartupActivity.this, GuideActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case DBADDRESS:
                    initDataBase();
                    break;
                case NOLOGIN:

                    break;

            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        provinceList=null;
        addressDao=null;
        result=null;
        intent=null;
        content=null;
        pushBean=null;
    }

    /**
     * 设置应用字号不受系统字号设置的影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
